<template>
  <view class="login-container">
    <!-- 背景装饰 -->
    <view class="bg-decoration">
      <view class="circle circle-1"></view>
      <view class="circle circle-2"></view>
      <view class="circle circle-3"></view>
    </view>

    <view class="login-box">
      <!-- 语言切换组件 -->
      <view class="lang-selector">
        <LangSelect />
      </view>

      <!-- Logo和标题区域 -->
      <view class="header-section">
        <view class="title">{{ t('login.login') }}</view>
        <view class="subtitle">OA管理系统</view>
      </view>

      <uni-forms ref="loginRef" :model="loginForm" :rules="loginRules" class="login-form">
        <!-- 用户名输入 -->
        <uni-forms-item name="username" class="form-item">
          <view class="input-wrapper">
            <uni-easyinput
              v-model="loginForm.username"
              :placeholder="t('login.username')"
              prefix-icon="person"
              class="custom-input"
            />
          </view>
        </uni-forms-item>

        <!-- 密码输入 -->
        <uni-forms-item name="password" class="form-item">
          <view class="input-wrapper">
            <uni-easyinput
              v-model="loginForm.password"
              type="password"
              :placeholder="t('login.password')"
              prefix-icon="locked"
              class="custom-input"
            />
          </view>
        </uni-forms-item>

        <!-- 记住密码 -->
        <view class="remember-section">
          <label class="remember-checkbox" >
            <checkbox @click="toggleRememberMe" :checked="loginForm.rememberMe" color="#409EFF" />
            <text class="remember-text">记住密码</text>
          </label>
          <text class="forgot-password">忘记密码？</text>
        </view>
        <!-- 登录按钮 -->
        <button class="login-btn" type="primary" @click="handleLogin" :loading="loading">
          <span v-if="!loading" class="btn-text">{{ t('login.login') }}</span>
          <span v-else class="btn-text">{{ t('login.logging') }}</span>
        </button>
      </uni-forms>
    </view>
  </view>
  <wrap-version-update ref="updateRef" id="702697090318405" @check="handleCheck" @error="handleError" @finish="handleFinish"></wrap-version-update>
</template>

<script setup lang="ts">
import { getCodeImg, getTenantList } from '@/api/login';
import { authBinding } from '@/api/system/social/auth';
import { useUserStore } from '@/store/modules/user';
import type { LoginData, TenantVO } from '@/api/types';
import { HttpStatus } from '@/enums/RespEnum';
import { ref, onMounted, version } from 'vue';
import { useI18n } from 'vue-i18n';
import LangSelect from '@/components/LangSelect/index.vue';
import { getLoginStorageData, setLoginStorageData, clearLoginStorageData } from '@/utils/storage';
import WrapVersionUpdate from '@/uni_modules/wrap-version-update/components/wrap-version-update/wrap-version-update.nvue'
const userStore = useUserStore();
const updateRef = ref<InstanceType<typeof WrapVersionUpdate>>();
const release = ref<any>({
  version: '',
});
const handleCheck = (res:any) => {
  release.value.version = res;
};
const handleError = (err) => {
};
const handleFinish = () => {
  release.value?.release();
};

const { t } = useI18n();

const loginForm = ref<LoginData>({
  username: 'admin',
  password: 'admin123',
  rememberMe: false,
  code: '',
  uuid: ''
} as LoginData);

const loginRules = {
  username: {
    rules: [{
      required: true,
      errorMessage: '请输入用户名'
    }]
  },
  password: {
    rules: [{
      required: true,
      errorMessage: '请输入密码'
    }]
  }
};

const codeUrl = ref('');
const loading = ref(false);
const captchaEnabled = ref(false);
const tenantEnabled = ref(false);
const redirect = ref('/pages/index');
const loginRef = ref();
const tenantList = ref<TenantVO[]>([]);
const tenantOptions = ref<{ value: string; text: string }[]>([]);

const toggleRememberMe = () => {
  loginForm.value.rememberMe = !loginForm.value.rememberMe;
};

const handleLogin = () => {
  loginRef.value?.validate().then(async (res: any) => {
    loading.value = true;
    // 保存或清除登录信息
    if (loginForm.value.rememberMe) {
      setLoginStorageData({
        username: loginForm.value.username,
        password: loginForm.value.password,
        rememberMe: loginForm.value.rememberMe
      });
    } else {
      clearLoginStorageData();
    }

    try {
      await userStore.login(loginForm.value);
      await userStore.getInfo();
      const redirectUrl = redirect.value || '/';
      uni.switchTab({
        url: '/pages/index'
      });
    } catch (err: any) {
      if (captchaEnabled.value) {
        getCode();
      }
      uni.showToast({
        title: err.message || '登录失败',
        icon: 'none'
      });
    } finally {
      loading.value = false;
    }
  }).catch((err: any) => {
  });
};

/**
 * 获取验证码
 */
const getCode = async () => {
  const res = await getCodeImg();
  const { data } = res;
  captchaEnabled.value = data.captchaEnabled === undefined ? true : data.captchaEnabled;
  if (captchaEnabled.value) {
    codeUrl.value = 'data:image/gif;base64,' + data.img;
    loginForm.value.uuid = data.uuid;
  }
};

const getLoginData = () => {
  try {
    const storageData = getLoginStorageData();
    // 如果有记住密码，使用存储的值，否则使用默认值
    if (storageData.rememberMe === 'true') {
      loginForm.value = {
        username: storageData.username,
        password: storageData.password,
        rememberMe: true,
        code: '',
        uuid: ''
      } as LoginData;
    } else {
      // 使用默认值
      loginForm.value = {
        username: '',
        password: '',
        rememberMe: false,
        code: '',
        uuid: ''
      } as LoginData;
    }
  } catch (error) {
    // 发生错误时使用默认值
    loginForm.value = {
      username: '',
      password: '',
      rememberMe: false,
      code: '',
      uuid: ''
    } as LoginData;
  }
};
onMounted(() => {
  getLoginData();
  updateRef.value?.check();
});

</script>

<style lang="scss" scoped>
.login-container {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20px;
  position: relative;
  overflow: hidden;
}

// 背景装饰
.bg-decoration {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  pointer-events: none;
  z-index: 0;

  .circle {
    position: absolute;
    border-radius: 50%;
    background: rgba(255, 255, 255, 0.1);
    animation: float 6s ease-in-out infinite;

    &.circle-1 {
      width: 80px;
      height: 80px;
      top: 10%;
      left: 10%;
      animation-delay: 0s;
    }

    &.circle-2 {
      width: 120px;
      height: 120px;
      top: 70%;
      right: 10%;
      animation-delay: 2s;
    }

    &.circle-3 {
      width: 60px;
      height: 60px;
      top: 30%;
      right: 30%;
      animation-delay: 4s;
    }
  }
}

@keyframes float {
  0%, 100% {
    transform: translateY(0px);
  }
  50% {
    transform: translateY(-20px);
  }
}

.login-box {
  width: 100%;
  max-width: 420px;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-radius: 20px;
  padding: 40px 30px;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
  position: relative;
  z-index: 1;
  border: 1px solid rgba(255, 255, 255, 0.2);
}

.lang-selector {
  position: absolute;
  top: 20px;
  right: 20px;
  z-index: 2;
}

// 头部区域
.header-section {
  text-align: center;
  margin-bottom: 40px;

  .logo-container {
    margin-bottom: 20px;

    .logo-icon {
      width: 80px;
      height: 80px;
      background: linear-gradient(135deg, #409EFF, #36CFC9);
      border-radius: 20px;
      display: flex;
      align-items: center;
      justify-content: center;
      margin: 0 auto;
      box-shadow: 0 10px 30px rgba(64, 158, 255, 0.3);

      .logo-text {
        font-size: 36px;
        font-weight: bold;
        color: white;
      }
    }
  }

  .title {
    font-size: 28px;
    font-weight: 600;
    color: #2c3e50;
    margin-bottom: 8px;
  }

  .subtitle {
    font-size: 14px;
    color: #7f8c8d;
    opacity: 0.8;
  }
}

// 表单样式
.login-form {
  .form-item {
    margin-bottom: 20px;

    .input-wrapper {
      position: relative;

      .custom-input {
        border-radius: 12px;
        border: 2px solid #e8f4fd;
        background-color: #f8fbff;
        transition: all 0.3s ease;

        &:focus {
          border-color: #409EFF;
          background-color: #fff;
          box-shadow: 0 0 0 3px rgba(64, 158, 255, 0.1);
        }
      }
    }
  }
}

// 记住密码区域
.remember-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: 25px 0;

  .remember-checkbox {
    display: flex;
    align-items: center;
    cursor: pointer;

    .remember-text {
      margin-left: 8px;
      font-size: 14px;
      color: #606266;
    }
  }

  .forgot-password {
    font-size: 14px;
    color: #409EFF;
    cursor: pointer;
    text-decoration: none;

    &:hover {
      text-decoration: underline;
    }
  }
}

// 登录按钮
.login-btn {
  width: 100%;
  height: 50px;
  background: linear-gradient(135deg, #409EFF, #36CFC9);
  border: none;
  border-radius: 12px;
  font-size: 16px;
  font-weight: 600;
  color: white;
  margin-top: 10px;
  box-shadow: 0 8px 20px rgba(64, 158, 255, 0.3);
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;

  &::before {
    content: '';
    position: absolute;
    top: 0;
    left: -100%;
    width: 100%;
    height: 100%;
    background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.2), transparent);
    transition: left 0.5s;
  }

  &:hover::before {
    left: 100%;
  }

  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 12px 25px rgba(64, 158, 255, 0.4);
  }

  &:active {
    transform: translateY(0);
  }

  .btn-text {
    position: relative;
    z-index: 1;
  }
}

// 响应式设计
@media (max-width: 480px) {
  .login-container {
    padding: 15px;
  }

  .login-box {
    padding: 30px 20px;
    border-radius: 16px;
  }

  .header-section {
    .logo-container .logo-icon {
      width: 60px;
      height: 60px;

      .logo-text {
        font-size: 28px;
      }
    }

    .title {
      font-size: 24px;
    }
  }
}
</style>
